package cn.edu.bupt.thymeleaf.examples.controller;

import cn.edu.bupt.thymeleaf.examples.entities.Comment;
import cn.edu.bupt.thymeleaf.examples.entities.Product;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/product")
public class ProductController {

    private final Map<Integer, Product> productsMap;

    public ProductController() {
        this.productsMap = new LinkedHashMap<>();
        final Product prod1 = new Product(1, "Fresh Sweet Basil", true, new BigDecimal("4.99"));
        final Product prod2 = new Product(2, "Italian Tomato", false, new BigDecimal("1.25"));
        final Product prod3 = new Product(3, "Yellow Bell Pepper", true, new BigDecimal("2.50"));
        final Product prod4 = new Product(4, "Old Cheddar", true, new BigDecimal("18.75"));
        final Product prod5 = new Product(5, "Extra Virgin Coconut Oil", true, new BigDecimal("6.34"));

        this.productsMap.put(prod1.getId(), prod1);
        this.productsMap.put(prod2.getId(), prod2);
        this.productsMap.put(prod3.getId(), prod3);
        this.productsMap.put(prod4.getId(), prod4);
        this.productsMap.put(prod5.getId(), prod5);

        prod2.getComments().add(new Comment(1, "I'm so sad this product is no longer available!"));
        prod2.getComments().add(new Comment(2, "When do you expect to have it back?"));

        prod5.getComments().add(new Comment(3, "Very tasty! I'd definitely buy it again!"));
        prod5.getComments().add(new Comment(4, "My kids love it!"));

    }

    @GetMapping("/list")
    public String listProducts(Model model){
        List<Product> allProducts = new ArrayList<>(this.productsMap.values());
        model.addAttribute("prods",allProducts);
        return "product/list";

    }

    @GetMapping("/comments")
    public String showProductComments(Model model, @RequestParam("prodId") Integer prodId){
        Product product = this.productsMap.get(prodId);
        model.addAttribute("prod",product);
        return "product/comments";

    }

}